package com.lingyistudio.common.util;


import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author :  LingYi
 * @ClassName:
 * @Date :   2019/6/23
 */
@Slf4j
public class AESModel {
    private static AESModel aesModel = null;
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding"; //算法
    private static String aesKey = "";
    private static String aesOldKey = "";
    private static ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
    private static char[] publicchar = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
            'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
            'y', 'z'
    };

    private AESModel() {} ;

    public static AESModel getAESModel() {
        if (aesModel == null) {
            synchronized (TimeModel.class) {
                if (aesModel == null) {
                    log.info("AESModel初始化");
                    aesModel = new AESModel();
                    aesModel.setKEY();
                    return aesModel;
                }
            }
        }
        return aesModel;
    }

    public static String getAesKey() {
        return aesKey;
    }

    public void setKEY() {
        aesOldKey = aesKey;
        aesKey = "" +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)] +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)] +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)] +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)] +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)] +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)] +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)] +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)] +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)] +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)] +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)] +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)] +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)] +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)] +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)] +
                publicchar[threadLocalRandom.nextInt(0, publicchar.length)];
        log.info("setKEY  旧密码："+ aesOldKey +"  新密码:"+aesKey);
    }

    public static byte[] base64Decode(String base64Code) {  //String转byte[]  解密1转换原文
        return base64Code == null ? null : (base64Code.length() < 1 ? null : Base64.getDecoder().decode(base64Code));
    }

    public static String base64Encode(byte[] bytes) {  //byte[]转String 加密1返回值
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception { //加密2
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        return cipher.doFinal(content.getBytes("utf-8"));
    }

    public static String aesEncrypt(String content, String encryptKey) {  //加密1
        log.info("aesEncrypt 使用："+encryptKey+"   加密：" +content);
        try {
            return base64Encode(aesEncryptToBytes(content, encryptKey));
        } catch (Exception e) {
            log.info("aesEncrypt  "+String.valueOf(e));
        }
        return null;
    }

    public static String aesDecrypt(String encryptStr, String decryptKey) {  //解密1
        try {
            byte[] encryptBytes = base64Decode(encryptStr);
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
            byte[] decryptBytes = cipher.doFinal(encryptBytes);
            return new String(decryptBytes, "utf-8");
        } catch (Exception e) {
            log.info("aesDecrypt 使用："+decryptKey+"   解密："+encryptStr);
            log.info("aesDecrypt  "+String.valueOf(e));
        }
        return null;
    }

    //使用默认的密码进行解密，当使用现在的密码不对时，使用上次使用的密码进行解密。解决网络延迟问题
    public static String aesDecrypt(String content) {
        String str = aesDecrypt(content, aesKey);
        if (str == null ) {
            str = aesDecrypt(content, aesOldKey);
        }
        return str;
    }

    //使用默认的密码进行加密
    public static String aesEncrypt(String content) {

        String str = aesEncrypt(content, aesKey);
        log.info("加密结果： "+str);
        return str;
    }
}
